from fastapi import APIRouter, Query, Path, Body, Request, HTTPException
from fastapi import APIRouter, Path, Query, Body
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime

from db import Db
from models import ResponseModel, ResponseList
from schemas.family_tree_schema import (
    FamilyTreeCreate, FamilyTreeUpdate, FamilyTreeInfo, FamilyTreeQuery,
    FamilyTreeWithRelations, FamilyTreeListResponse,
    FamilyRelationshipCreate, FamilyRelationshipInfo, FamilyRelationshipQuery,
    NearbyGraveQuery, GraveLocationSimple,
    BatchFamilyRelationshipCreate, BatchCreateResult,
    AncestorsDescendantsQuery, GenerationQuery, StructureQuery
)
from curd.family_tree import FamilyTreeCRUD, FamilyRelationshipCRUD
from utils.log_utils import logger

# 创建APIRouter实例
family_tree_router = APIRouter(
    prefix='/family-tree',
    tags=['family-tree 族谱管理']
)


# ========== 族谱成员管理接口 ==========

@family_tree_router.post('/members', summary="创建族谱成员")
def create_family_member(
    member: FamilyTreeCreate = Body(..., description="族谱成员信息"),
    db: Session = Db
):
    """创建族谱成员"""
    try:
        # 创建族谱成员
        db_member = FamilyTreeCRUD.create_family_member(db, member)
        
        logger.info(f"创建族谱成员: {db_member['name']}")
        return ResponseModel.success(data=db_member, message="创建族谱成员成功")
    
    except Exception as e:
        logger.error(f"创建族谱成员失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"创建族谱成员失败: {str(e)}")


@family_tree_router.get('/members/{member_id}', summary="获取族谱成员详情")
def get_family_member(
    member_id: str = Path(..., description="成员ID"),
    db: Session = Db
):
    """获取族谱成员详情"""
    try:
        db_member = FamilyTreeCRUD.get_family_member(db, member_id)
        
        if not db_member:
            return ResponseModel.error(code=404, message="族谱成员不存在")
        
        return ResponseModel.success(data=db_member, message="获取族谱成员详情成功")
    
    except Exception as e:
        logger.error(f"获取族谱成员详情失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"获取族谱成员详情失败: {str(e)}")


@family_tree_router.post('/members-list', summary="获取族谱成员列表")
def get_family_members(
    query: FamilyTreeQuery = Body(..., description="查询条件"),
    db: Session = Db
):
    """获取族谱成员列表（支持分页和筛选）"""
    try:
        members, total = FamilyTreeCRUD.get_family_members(db, query)
        
        # 计算总页数
        total_pages = (total + query.page_size - 1) // query.page_size
        
        response_data = {
            'pageIndex': query.page_index,
            'pageSize': query.page_size,
            'total': total,
            'totalPages': total_pages,
            'data': members
        }
        
        return ResponseList.success(data=response_data, message="获取族谱成员列表成功")
    
    except Exception as e:
        logger.error(f"获取族谱成员列表失败: {str(e)}")
        return ResponseList.error(code=500, message=f"获取族谱成员列表失败: {str(e)}")


@family_tree_router.post('/members-update/{member_id}', summary="更新族谱成员")
def update_family_member(
    member_id: str = Path(..., description="成员ID"),
    member_update: FamilyTreeUpdate = Body(..., description="更新信息"),
    db: Session = Db
):
    """更新族谱成员信息"""
    try:
        # 更新族谱成员
        db_member = FamilyTreeCRUD.update_family_member(db, member_id, member_update)
        
        if not db_member:
            return ResponseModel.error(code=404, message="族谱成员不存在")
        
        logger.info(f"更新族谱成员: {db_member['name']}")
        return ResponseModel.success(data=db_member, message="更新族谱成员成功")
    
    except ValueError as ve:
        logger.error(f"更新族谱成员参数错误: {str(ve)}")
        return ResponseModel.error(code=400, message=f"参数错误: {str(ve)}")
    except Exception as e:
        logger.error(f"更新族谱成员失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"更新族谱成员失败: {str(e)}")


@family_tree_router.delete('/members/{member_id}', summary="删除族谱成员")
def delete_family_member(
    member_id: str = Path(..., description="成员ID"),
    db: Session = Db
):
    """删除族谱成员（软删除）"""
    try:
        # 删除族谱成员
        result = FamilyTreeCRUD.delete_family_member(db, member_id)
        
        if not result:
            return ResponseModel.error(code=404, message="族谱成员不存在")
        
        logger.info(f"删除族谱成员: {member_id}")
        return ResponseModel.success(message="删除族谱成员成功")
    
    except Exception as e:
        logger.error(f"删除族谱成员失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"删除族谱成员失败: {str(e)}")


@family_tree_router.post('/members-generation/{generation}', summary="根据代数获取族谱成员")
def get_family_tree_by_generation(
    generation: int = Path(..., description="代数", ge=1),
    query: GenerationQuery = Body(..., description="查询条件"),
    db: Session = Db
):
    """根据代数获取族谱成员（支持多租户筛选）"""
    try:
        members = FamilyTreeCRUD.get_family_tree_by_generation(db, generation, query.shop_id, query.tenant_id)
        return ResponseModel.success(data=members, message="获取指定代数族谱成员成功")
    
    except Exception as e:
        logger.error(f"获取指定代数族谱成员失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"获取指定代数族谱成员失败: {str(e)}")


@family_tree_router.get('/members-search', summary="搜索族谱成员")
def search_family_members(
    keyword: str = Query(..., description="姓名关键词"),
    limit: int = Query(20, description="返回数量限制", ge=1, le=100),
    db: Session = Db
):
    """搜索族谱成员（按姓名）"""
    try:
        members = FamilyTreeCRUD.search_family_members(db, keyword, limit)
        return ResponseModel.success(data=members, message="搜索族谱成员成功")
    
    except Exception as e:
        logger.error(f"搜索族谱成员失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"搜索族谱成员失败: {str(e)}")


@family_tree_router.post('/graves-nearby', summary="获取附近墓地")
def get_nearby_graves(
    query: NearbyGraveQuery = Body(..., description="地理位置查询参数"),
    db: Session = Db
):
    """
    根据地理位置获取附近的墓地（分页）
    
    - **longitude**: 中心点经度坐标（-180到180）
    - **latitude**: 中心点纬度坐标（-90到90）
    - **radius**: 查找半径（米），默认500米，最大50公里
    - **page_index**: 页码，从1开始
    - **page_size**: 每页数量，默认10，最妤1000
    - **shop_id**: 可选，按店铺筛选
    - **tenant_id**: 可选，按租户筛选
    
    返回结果按距离从近到远排序。
    返回字段：姓名、第几代、性别、ID、墓地坐标、墓地地址、距离。
    详细信息请通过ID查询单个成员。
    """
    try:
        # 查找附近墓地
        graves, total = FamilyTreeCRUD.get_nearby_graves(db, query)
        
        # 计算总页数
        total_pages = (total + query.page_size - 1) // query.page_size
        
        # 构建分页响应数据
        response_data = {
            'pageIndex': query.page_index,
            'pageSize': query.page_size,
            'total': total,
            'totalPages': total_pages,
            'data': graves
        }
        
        logger.info(f"获取附近墓地: 中心点({query.latitude}, {query.longitude}), 半径{query.radius}米, 第{query.page_index}页, 每页{query.page_size}条, 总共{total}个墓地")
        return ResponseList.success(data=response_data, message="获取附近墓地成功")
    
    except ValueError as ve:
        logger.error(f"参数验证错误: {str(ve)}")
        return ResponseList.error(code=400, message=str(ve))
    except Exception as e:
        logger.error(f"获取附近墓地失败: {str(e)}")
        return ResponseList.error(code=500, message=f"获取附近墓地失败: {str(e)}")


# ========== 家族关系管理接口 ==========

@family_tree_router.post('/relationships', summary="创建家族关系")
def create_relationship(
    relationship: FamilyRelationshipCreate = Body(..., description="家族关系信息"),
    db: Session = Db
):
    """创建家族关系"""
    try:
        # 创建关系（CURD层会进行数据完整性检查）
        db_relationship = FamilyRelationshipCRUD.create_relationship(db, relationship)
        
        logger.info(f"创建家族关系: {relationship.person_id} -> {relationship.related_person_id} ({relationship.relationship_type})")
        return ResponseModel.success(data=db_relationship, message="创建家族关系成功")
    
    except ValueError as ve:
        logger.error(f"数据验证错误: {str(ve)}")
        return ResponseModel.error(code=400, message=str(ve))
    except Exception as e:
        logger.error(f"创建家族关系失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"创建家族关系失败: {str(e)}")


@family_tree_router.post('/relationships-batch', summary="批量创建家族关系")
def batch_create_relationships(
    batch_data: BatchFamilyRelationshipCreate = Body(..., description="批量家族关系信息"),
    db: Session = Db
):
    """
    批量创建家族关系
    
    - **relationships**: 关系列表，每个包含 person_id、related_person_id、relationship_type
    - **create_by**: 创建人 ID（可选）
    
    功能特点：
    - 自动过滤重复关系（双向检查）
    - 验证成员存在性
    - 返回成功和失败的详细信息
    - 支持部分成功创建
    """
    try:
        # 批量创建关系
        result = FamilyRelationshipCRUD.batch_create_relationships(
            db, 
            batch_data.relationships, 
            batch_data.create_by
        )
        
        logger.info(f"批量创建家族关系: 请求{result['total_requested']}个, 成功{result['created_count']}个, 跳过{result['skipped_count']}个")
        
        # 根据结果决定响应类型
        if result['created_count'] == 0:
            return ResponseModel.error(
                code=400, 
                message="所有关系都无法创建", 
                data=result
            )
        elif result['skipped_count'] == 0:
            return ResponseModel.success(
                data=result, 
                message=f"所有关系都创建成功，共{result['created_count']}个"
            )
        else:
            return ResponseModel.success(
                data=result, 
                message=f"部分创建成功: 成功{result['created_count']}个, 跳过{result['skipped_count']}个"
            )
    
    except Exception as e:
        logger.error(f"批量创建家族关系失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"批量创建家族关系失败: {str(e)}")


@family_tree_router.get('/relationships-person/{person_id}', summary="获取某人的所有关系")
def get_relationships_by_person(
    person_id: str = Path(..., description="人员ID"),
    db: Session = Db
):
    """获取某人的所有关系"""
    try:
        relationships = FamilyRelationshipCRUD.get_relationships_by_person(db, person_id)
        return ResponseModel.success(data=relationships, message="获取人员关系成功")
    
    except Exception as e:
        logger.error(f"获取人员关系失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"获取人员关系失败: {str(e)}")


@family_tree_router.post('/relationships-repair-names', summary="修复关系表姓名缓存")
def repair_relationship_names(
    db: Session = Db
):
    """
    修复关系表中的姓名缓存字段
    用于填充现有关系记录的姓名缓存，提高查询性能
    """
    try:
        result = FamilyRelationshipCRUD.repair_relationship_names(db)
        
        logger.info(f"修复关系姓名缓存: {result['message']}")
        return ResponseModel.success(data=result, message=result['message'])
    
    except Exception as e:
        logger.error(f"修复关系姓名缓存失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"修复关系姓名缓存失败: {str(e)}")


@family_tree_router.post('/relationships-list', summary="获取关系列表")
def get_relationships(
    query: FamilyRelationshipQuery = Body(..., description="查询条件"),
    db: Session = Db
):
    """获取关系列表（支持分页和筛选）"""
    try:
        relationships, total = FamilyRelationshipCRUD.get_relationships(db, query)
        
        # 计算总页数
        total_pages = (total + query.page_size - 1) // query.page_size
        
        response_data = {
            'pageIndex': query.page_index,
            'pageSize': query.page_size,
            'total': total,
            'totalPages': total_pages,
            'data': relationships
        }
        
        return ResponseList.success(data=response_data, message="获取关系列表成功")
    
    except Exception as e:
        logger.error(f"获取关系列表失败: {str(e)}")
        return ResponseList.error(code=500, message=f"获取关系列表失败: {str(e)}")


@family_tree_router.delete('/relationships/{relationship_id}', summary="删除家族关系")
def delete_relationship(
    relationship_id: str = Path(..., description="关系ID"),
    db: Session = Db
):
    """删除家族关系"""
    try:
        # 删除关系
        result = FamilyRelationshipCRUD.delete_relationship(db, relationship_id)
        
        if not result:
            return ResponseModel.error(code=404, message="家族关系不存在")
        
        logger.info(f"删除家族关系: {relationship_id}")
        return ResponseModel.success(message="删除家族关系成功")
    
    except Exception as e:
        logger.error(f"删除家族关系失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"删除家族关系失败: {str(e)}")


# ========== 族谱结构接口 ==========

@family_tree_router.post('/structure', summary="获取族谱树形结构")
def get_family_tree_structure(
    query: StructureQuery = Body(..., description="查询条件"),
    db: Session = Db
):
    """获取族谱树形结构（支持多租户筛选）"""
    try:
        family_tree = FamilyRelationshipCRUD.get_family_tree_structure(
            db, query.root_person_id, query.shop_id, query.tenant_id
        )
        return ResponseModel.success(data=family_tree, message="获取族谱树形结构成功")
    
    except Exception as e:
        logger.error(f"获取族谱树形结构失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"获取族谱树形结构失败: {str(e)}")


@family_tree_router.post('/descendants/{person_id}', summary="获取某人的后代")
def get_descendants(
    person_id: str = Path(..., description="人员ID"),
    query: AncestorsDescendantsQuery = Body(..., description="查询条件"),
    db: Session = Db
):
    """获取某人的后代（递归查询，支持多租户筛选）"""
    try:
        descendants = FamilyRelationshipCRUD.get_descendants(
            db, person_id, query.max_generations, query.shop_id, query.tenant_id
        )
        return ResponseModel.success(data=descendants, message="获取后代信息成功")
    
    except Exception as e:
        logger.error(f"获取后代信息失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"获取后代信息失败: {str(e)}")


@family_tree_router.post('/ancestors/{person_id}', summary="获取某人的祖先")
def get_ancestors(
    person_id: str = Path(..., description="人员ID"),
    query: AncestorsDescendantsQuery = Body(..., description="查询条件"),
    db: Session = Db
):
    """获取某人的祖先（递归查询，支持多租户筛选）"""
    try:
        ancestors = FamilyRelationshipCRUD.get_ancestors(
            db, person_id, query.max_generations, query.shop_id, query.tenant_id
        )
        return ResponseModel.success(data=ancestors, message="获取祖先信息成功")
    
    except Exception as e:
        logger.error(f"获取祖先信息失败: {str(e)}")
        return ResponseModel.error(code=500, message=f"获取祖先信息失败: {str(e)}")